import {
    Compiler,
    sky_module,
    wrapPlugin,
} from "https://fastly.jsdelivr.net/npm/rollup-web@4.5.0";
import { FSFetcher } from "https://fastly.jsdelivr.net/npm/rollup-web@4.5.0/dist/adapter/Fetcher/FSFetcher.js";
import {
    BlocksToCode,
    initModuleBlocks,
    InjectEnv,
} from "http://127.0.0.1:3000/packages/blockly/dist/index.mjs";
InjectEnv();
initModuleBlocks();
//TODO 未进行测试
export const _blockly = ({ log }) => {
    return {
        name: "blockly",
        /** wrapPlugin 提供了 extensions 守护，id 必然是符合的 */
        async transform(code, id) {
            try {
                const Code = BlocksToCode(JSON.parse(code));
                log && log(id, Code);
                return Code;
            } catch (e) {
                console.error(e);
            }
        },
    };
};
/* Babel 桥接插件 */
const blockly = wrapPlugin(_blockly, {
    extensions: [".block"],
});

const config = {
    plugins: [
        blockly({
            log(id, code) {
                console.log(id, code);
            },
        }),
        {
            resolveId(id) {
                if (id === "@forsee/mocha") {
                    return id;
                }
            },
            load(id) {
                if (id === "@forsee/mocha") {
                    const list = ["describe", "it", "test", "expect"];
                    return list
                        .map(
                            (i) =>
                                `export const ${i} = globalThis.__Mocha__.${i};`
                        )
                        .join("");
                }
            },
        },
        sky_module({
            cdn: "https://esm.sh/",
        }),
    ],
};
const compiler = new Compiler(config, {
    root: "http://127.0.0.1:3000/",
    // 用于为相对地址添加绝对地址
    // 为没有后缀名的 url 添加后缀名
    extensions: [".js", ".mjs", ".block"],
    log(url) {
        console.log("%c Download ==> " + url, "color:green");
    },
    adapter: FSFetcher({
        // ! 必须要标志清楚你的工作区间
        storeTag: "first-test",
    }),
    extraBundle: [],
    ignore: [],
});
console.log("compiler success done!");
compiler.useWorker();
